package app


import (
"context"
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"k8s.io/klog"
"os"
"wanlei/auto_click_server/cmd/app/options"
"wanlei/auto_click_server/pkg"
)

func NewServerCommand() *cobra.Command {
	cfg := &options.Config{}
	cmd := &cobra.Command{
		Use:  "mydumper uploader",
		Long: "The s3uploader tool s3uploader mydumper data to minio",
		Run: func(cmd *cobra.Command, args []string) {
			if err := run(cmd, args, cfg); err != nil {
				fmt.Fprintf(os.Stderr, "%v\v", err)
				os.Exit(1)
			}
		},
	}
	cfg.AddFlags(cmd.Flags())
	return cmd
}

func run(cmd *cobra.Command, args []string, config *options.Config) error {
	// logs the flags in the flagset
	cmd.Flags().VisitAll(func(flag *pflag.Flag) {
		klog.V(1).Infof("FLAG: --%s=%q", flag.Name, flag.Value)
	})


	server, err := pkg.NewServer(config.StepsFile,config.ResultDir,config.ImagesPath,config.ImageX,config.ImageY,config.ImageWidth,config.ImageHeight,config.MaxAppLifeTime)
	if err != nil {
		klog.Errorf("new server with error %v", err)
		return err
	}
	ctx, _ := context.WithCancel(context.Background())
	server.Run(ctx)
	return nil
}